package com.gitee.sparta.core.cluster;

import cn.hutool.core.thread.GlobalThreadPool;
import com.gitee.sparta.core.bean.cluster.ClusterCmd;
import com.gitee.sparta.core.bean.cluster.ClusterProtocol;
import com.gitee.sparta.core.cluster.balance.LoadBalance;
import com.gitee.sparta.core.property.SpartaCoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.context.ApplicationEventPublisher;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * <p>
 *      抽象的从节点信息
 * </p>
 *
 * @author zyred
 * @since v 0.0.2
 */
@Slf4j
public abstract class AbstractClusterFollower {

    protected static final BlockingQueue<ClusterProtocol> SEND_LEADER_QUEUE = new LinkedBlockingQueue<>();

    protected final RedissonClient client;
    protected final LoadBalance loadBalance;
    protected final SpartaCoreProperties properties;
    protected final ApplicationEventPublisher eventPublisher;


    public AbstractClusterFollower(ApplicationEventPublisher eventPublisher,
                              RedissonClient client,
                              SpartaCoreProperties properties,
                              LoadBalance loadBalance) {
        this.properties = properties;
        this.client = client;
        this.loadBalance = loadBalance;
        this.eventPublisher = eventPublisher;

        this.startSenderLeader();
    }

    /**
     * 构建 follower 节点
     *
     * @param leaderHost    leader host
     * @param leaderPort    leader port
     * @throws Exception    Exception
     */
    abstract public void buildFollower(String leaderHost, int leaderPort) throws Exception;


    /**
     * 集群发生了重新选举, 原本是 follower 角色的连接的是 oldLeader
     * 经过一轮的选举后, oldLeader 被 newLeader 代替, 所以选举后依然是
     * follower 的需要重新连接  newLeader, 连接 newLeader 之前需要关
     * 闭对 oldLeader 的网络连接
     *
     * @throws IOException  关闭异常
     */
    abstract public void closeForOldLeader() throws IOException;

    /**
     * 关闭发送线程
     *
     * NIO 才需要关闭发送线程, netty 是不需要的
     */
    public void closeSendThread() {
        ClusterProtocol protocol = ClusterProtocol
                .defaultValue(ClusterCmd.WORKER_SEND_STOP);
        SEND_LEADER_QUEUE.add(protocol);
        log.info("[Sparta] Close send to leader thread.");
    }

    /**
     * 实际写出数据到 leader 节点
     *
     * @param protocol      协议对象
     * @throws Exception    异常
     */
    abstract protected void doWriteLeader(ClusterProtocol protocol) throws Exception;

    /**
     * 发送消息到 queue 中
     *
     * @param protocol  协议对象
     */
    public static void sendQueue(ClusterProtocol protocol) {
        SEND_LEADER_QUEUE.add(protocol);
    }

    /**
     * 启动发送线程
     */
    @SuppressWarnings("all")
    private void startSenderLeader() {
        GlobalThreadPool.execute(() -> {
            while (!Thread.interrupted()) {
                ClusterProtocol protocol = null;
                try {
                    protocol = SEND_LEADER_QUEUE.take();
                    // 收到的是停止指令
                    if (Objects.equals(protocol.getCmd(), ClusterCmd.WORKER_SEND_STOP)) {
                        Thread.currentThread().interrupt();
                        return;
                    }

                    this.doWriteLeader(protocol);

                    // 收到的是宕机指令
                    if (Objects.equals(protocol.getCmd(), ClusterCmd.FOLLOWER_SHUTDOWN)) {
                        this.closeForOldLeader();
                        Thread.currentThread().interrupt();
                    }
                } catch (Exception e) {
                    // take 方法内中断后，中断标志位复位
                    if (e instanceof InterruptedException) {
                        Thread.currentThread().interrupt();
                    }
                    if (Objects.nonNull(protocol)) {
                        SEND_LEADER_QUEUE.add(protocol);
                    }
                }
            }
            log.info("[Sparta] Follower sender thread stop : {}", Thread.currentThread().getName());
        });
    }
}
